$(function() {
    //主流程对象
    var mainCtrl = avalon.define({
        $id: "mainController",
        regionCode : "",
		branchCode : "",
        storeCode: "",
        isInStorage: "",
        curRegion: "", //查询后所对应的大区
        curBranch: "", //查询后所对应的分公司
        curStore: "", //查询后所对应的门店
        dataLen: 0, //判断导出是否置灰 0置灰
		allRegion : [], // 先记录下来模糊查询时需要用到
		allBranch : [], // 分公司
		allStore : [],// 门店
		exportParams:{},// 导出参数
        search: function() {
        	mainCtrl.regionCode = $("#magicRegion .m-id").val();
			mainCtrl.branchCode = $("#magicBranch .m-id").val();
            mainCtrl.storeCode = $("#magicStore .m-id").val();
            if(!mainCtrl.regionCode) {
                return;
            }
            opts.settings.searchParam = {
                "isInStorage": mainCtrl.isInStorage,
                "pageNo": 1,
                "pageSize": 10,
                "regionCode" : mainCtrl.regionCode,
				"branchCode" : mainCtrl.branchCode,
                "storeCode": mainCtrl.storeCode
            }
            
            mainCtrl.dataLen = 0;            
            exptTable.table.total = 0;
            
            mainCtrl.exportParams.isInStorage = mainCtrl.isInStorage;
            mainCtrl.exportParams.regionCode = mainCtrl.regionCode;
            mainCtrl.exportParams.branchCode = mainCtrl.branchCode;
            mainCtrl.exportParams.storeCode = mainCtrl.storeCode;
            
            exptTable.search(opts.settings.searchParam);
            checkDataLen();
        },
        exportPop: function() {
            if(mainCtrl.dataLen == 0) {
                return;
            }
            //如果总数据 小于 获取的导出限制值 说明数据量很小，直接导出 
            if(mainCtrl.dataLen <= popCtrl.gotNum) {
            	var exportURL = DI.exportSaleExpt + "?index=1";
            	if (mainCtrl.exportParams.isInStorage) {
            		exportURL += "&isInStorage=" + mainCtrl.exportParams.isInStorage;
            	}
            	if(mainCtrl.exportParams.regionCode) {
					exportURL += "&regionCode=" + mainCtrl.exportParams.regionCode;
				}
            	if(mainCtrl.exportParams.branchCode) {
	                exportURL += "&branchCode=" + mainCtrl.exportParams.branchCode;
	            }
            	if(mainCtrl.exportParams.storeCode) {
	                exportURL += "&storeCode=" + mainCtrl.exportParams.storeCode;
	            }
            	window.open(exportURL);
//                window.location = DI.exportSaleExpt + "?index=1&storeCode=" + mainCtrl.storeCode;
                return;
            }
            //0代表没有取过导出限制值，如果取过就不用再去取了
            if(popCtrl.gotNum == 0) {
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: DI.queryExptCSVLimit,
                    success: function(data) {
                        var num = data.data,
                            exportCount = Math.ceil(mainCtrl.dataLen / num),
                            countList = [],
                            startNum = 1;
                        popCtrl.gotNum = num;
                        //如果总数据 小于 获取的导出限制值 说明数据量很小，直接导出 
                        if(mainCtrl.dataLen <= popCtrl.gotNum) {
                        	var exportURL = DI.exportSaleExpt + "?index=1";
                        	if (mainCtrl.exportParams.isInStorage) {
                        		exportURL += "&isInStorage=" + mainCtrl.exportParams.isInStorage;
                        	}
                        	if(mainCtrl.exportParams.regionCode) {
            					exportURL += "&regionCode=" + mainCtrl.exportParams.regionCode;
            				}
                        	if(mainCtrl.exportParams.branchCode) {
            	                exportURL += "&branchCode=" + mainCtrl.exportParams.branchCode;
            	            }
                        	if(mainCtrl.exportParams.storeCode) {
            	                exportURL += "&storeCode=" + mainCtrl.exportParams.storeCode;
            	            }
                        	window.open(exportURL);
//                            window.location = DI.exportSaleExpt + "?index=1&storeCode=" + mainCtrl.storeCode+"&isInStorage="+mainCtrl.isInStorage;
                            return;
                        }
                        for(var i = 0; i < exportCount; i++) {
                            var endNum = startNum + (num - 1);
                            if(endNum > mainCtrl.dataLen) {
                                endNum = mainCtrl.dataLen;
                            }
                            countList.push(startNum + "~" + endNum);
                            startNum = endNum + 1;
                        }
                        popCtrl.exportCountList = countList;
                        $("#popup_cnt").show();
                    },
                    error: function(err) {
                        console.log(err);
                    }
                });
            } else {
                var num = popCtrl.gotNum,
	                exportCount = Math.ceil(mainCtrl.dataLen / num),
	                countList = [],
	                startNum = 1;
	            //如果总数据 小于 获取的导出限制值 说明数据量很小，直接导出 
	            if(mainCtrl.dataLen <= popCtrl.gotNum) {
	            	var exportURL = DI.exportSaleExpt + "?index=1";
	            	if (mainCtrl.exportParams.isInStorage) {
	            		exportURL += "&isInStorage=" + mainCtrl.exportParams.isInStorage;
	            	}
	            	if(mainCtrl.exportParams.regionCode) {
						exportURL += "&regionCode=" + mainCtrl.exportParams.regionCode;
					}
	            	if(mainCtrl.exportParams.branchCode) {
		                exportURL += "&branchCode=" + mainCtrl.exportParams.branchCode;
		            }
	            	if(mainCtrl.exportParams.storeCode) {
		                exportURL += "&storeCode=" + mainCtrl.exportParams.storeCode;
		            }
	            	window.open(exportURL);
	//                window.location = DI.exportSaleExpt + "?index=1&storeCode=" + mainCtrl.storeCode+"&isInStorage="+mainCtrl.isInStorage;
	                return;
	            }
	            for(var i = 0; i < exportCount; i++) {
	                var endNum = startNum + (num - 1);
	                if(endNum > mainCtrl.dataLen) {
	                    endNum = mainCtrl.dataLen;
	                }
	                countList.push(startNum + "~" + endNum);
	                startNum = endNum + 1;
	            }
	            popCtrl.exportCountList = countList;
                $("#popup_cnt").show();
            }
        }
    });
    //弹框对象
    var popCtrl = avalon.define({
        $id: "popController",
        gotNum: 0, //判断是否获取过导出限制值
        exportCountList: [],
        countIdx: 1,
        selCount: function() {
            popCtrl.countIdx = $(this).index() + 1;
            $(this).addClass("sel").siblings(".e-number").removeClass("sel");
        },
        exportList: function() {
            var index = popCtrl.countIdx;
        	var exportURL = DI.exportSaleExpt + "?index=" + index;
        	if (mainCtrl.exportParams.isInStorage) {
        		exportURL += "&isInStorage=" + mainCtrl.exportParams.isInStorage;
        	}
        	if(mainCtrl.exportParams.regionCode) {
				exportURL += "&regionCode=" + mainCtrl.exportParams.regionCode;
			}
        	if(mainCtrl.exportParams.branchCode) {
                exportURL += "&branchCode=" + mainCtrl.exportParams.branchCode;
            }
        	if(mainCtrl.exportParams.storeCode) {
                exportURL += "&storeCode=" + mainCtrl.exportParams.storeCode;
            }
        	window.open(exportURL);
//            window.location = DI.exportSaleExpt + "?index=" + index + "&storeCode=" + mainCtrl.storeCode+"&isInStorage="+mainCtrl.isInStorage;
        }
    });
    //表格实例化
    var exptTable = null;
    var opts = {
        targetId: "exptTable",
        templateId: "tableSaleExpt",
        settings: {
            url: DI.querySaleExptList,
            ajaxType: "json",
            sourceInterface: {
                INum: "totalSize",
                IData: "records"
            },
            paginationIndexName: {
                "peerpageRows": "pageSize",
                "currentPage": "pageNo"
            }
        }
    };

    var magicRegion = $('#magicRegion').magicSuggest({
		renderer : function(city) {
			return city.name;
		},
		placeholder : "选择大区",
		required : true,
		selectionStacked : true,
		expandOnFocus : true,
		selectionRenderer : function(city) {
			return city.name;
		}
	});
	var magicBranch = $('#magicBranch').magicSuggest({
		renderer : function(city) {
			return city.name;
		},
		placeholder : "选择分公司",
		required : true,
		selectionStacked : true,
		expandOnFocus : true,
		selectionRenderer : function(city) {
			return city.name;
		}
	});
    var magicStore = $('#magicStore').magicSuggest({
        renderer: function(city) {
            return city.name;
        },
        placeholder: "选择门店编号/名称",
        required: true,
        selectionStacked: true,
        expandOnFocus: true,
        selectionRenderer: function(city) {
            return city.name;
        }
    });
    function checkDataLen(){
        var intervalSource = setInterval(function() {
            mainCtrl.dataLen = exptTable.table.total;
            if(mainCtrl.dataLen > 0) {
                clearInterval(intervalSource);
                mainCtrl.curRegion = exptTable.table.sources[0].regionName;
                mainCtrl.curBranch = exptTable.table.sources[0].branchName;
                mainCtrl.curStore = exptTable.table.sources[0].storeName;
            }
        }, 100);
    }
    function getAllStores() {
        $(".loadData").show();
        $.ajax({
            type: "post",
            dataType: "json",
            url: DI.queryOrgTree,
            success: function(data) {
                $(".loadData").hide();

                var allStoreData = data.data;
                var alljsonData = [];
                for(var i = 0; i < allStoreData.length; i++) {
                    if(allStoreData[i].level == 3) {
                        alljsonData.push({
                            id: allStoreData[i].id,
                            name: allStoreData[i].id + "-" + allStoreData[i].text
                        });
                    }
                }
                magicStore.setData(alljsonData);
                $(magicStore).on(
                    'selectionchange',
                    function(e, cb, s) {
                        var str = cb.getValue();
                        mainCtrl.storeCode = str[0];
                    });

                if(exptTable == null) {
                    magicStore.setSelection(alljsonData[0]);
                    opts.settings.searchParam = {
                        "isInStorage": mainCtrl.isInStorage,
                        "pageNo": 1,
                        "pageSize": 10,
                        "storeCode": mainCtrl.storeCode
                    }
                    exptTable = SwiftUI.swiftTable.getInstance(opts);
                    checkDataLen();
                }
            },
            error: function(err) {
                console.log(err);
            }
        });
    }
    
  //FIXME 门店选择联动方式修改
	function getRegionBranch() {
		$(".loadData").show();
		$.ajax({
					type : "post",
					dataType : "json",
					url : DI.queryOrgTree,
					success : function(data) {
						$(".loadData").hide();

						for (var i = 0; i < data.data.length; i++) {
							// 1是大区 2是分公司
							if (data.data[i].level == 1) {
								var regionObj = data.data[i];
								mainCtrl.allRegion.push(regionObj);
							} else if (data.data[i].level == 2) {
								var branchObj = data.data[i];
								mainCtrl.allBranch.push(branchObj);
							} else if (data.data[i].level == 3) {
								var storeObj = data.data[i];
								mainCtrl.allStore.push(storeObj);
							}
						}
						var allRegionData = [];
						for (var i = 0; i < mainCtrl.allRegion.length; i++) {
							allRegionData.push({
								id : mainCtrl.allRegion[i].id,
								name : mainCtrl.allRegion[i].id + "-"
										+ mainCtrl.allRegion[i].text
							});
						}
						
						$(magicRegion)
								.on('selectionchange',
										function(e, cb, s) {
											var str = cb.getValue(), 
												bcode = $("#magicBranch .m-id").val(), 
												pid = $("#magicBranch .m-pid").val(), 
												regionid = str[0] == undefined ? "" : str[0];
											mainCtrl.regionCode = regionid;
											// 获取该大区下的所有分公司
											getBranchByCode(regionid);
											
											magicBranch.clear();
											magicBranch.collapse();
											magicStore.clear();
											magicStore.collapse();
//											magicStore.setData([]);
//											magicStore.disable();
											if (s.length > 0) {
												magicBranch.enable();
												getStoresByCode(mainCtrl.branchCode == undefined ? "" :mainCtrl.branchCode );
											} else {
												magicBranch.setData([]);
												magicBranch.disable();
											}
										});
						magicRegion.setData(allRegionData);
						magicRegion.setSelection(allRegionData[0]);
						$(magicBranch).on('selectionchange',
										function(e, cb, s) {
											var pid = $("#magicBranch .m-pid").val(), 
												rid = $("#magicRegion .m-id").val(), 
										          scode = $("#magicStore .m-id").val(),
						                            bcode = $("#magicBranch .m-id").val(),
						                            spid = $("#magicStore .m-pid").val(),
												str = cb.getValue();
											mainCtrl.branchCode = str[0];
								            //如果门店不为空，且门店父id不是当前分公司id  清空
					                        if(scode && spid != bcode) {
					                            magicStore.clear();
					                            magicStore.input.focus();
					                        }
					                    	getStoresByCode(mainCtrl.branchCode == undefined ? "" :mainCtrl.branchCode );
											
//											if (s.length > 0) {
//												magicStore.enable();
//											} else {
//												magicStore.setData([]);
//												magicStore.disable();
//											}
										});
						
						getStoresByCode("");
						   $(magicStore).on(
			                        'selectionchange',
			                        function(e, cb, s) {
			                            var str = cb.getValue(),
			                                pid = $("#magicStore .m-pid").val(),
			                                branchid1 = $("#magicBranch .m-id").val();
			                            mainCtrl.storeCode = str[0];
			                            //如果当前选择门店的时候 pid 不等于分公司id，则要重新设置分公司id
			                            if(pid){
			                            	if(pid != branchid1) {
			                            		var allBranchList = mainCtrl.allBranch,
			                            		allBranchLen = allBranchList.length,
			                            		newBranch = [];
			                            		if(pid) {
			                            			var branchObj = "";
			                            			for(var i = 0; i < allBranchLen; i++) {
			                            				var branchid = allBranchList[i].id;
			                            				if(branchid == pid) {
			                            					var branchTxt = allBranchList[i].text,
			                            					branchName = branchid + "-" + branchTxt;
			                            					branchObj = {
			                            							"id": branchid,
			                            							"name": branchName,
			                            							"pid": allBranchList[i].pid
			                            					}
			                            					break;
			                            				}
			                            			}
			                            			if(branchObj != "") {
			                            				magicBranch.setSelection(branchObj)
			                            			}
			                            		}
			                            	}
			                            }
			                            magicBranch.collapse();
			                        });
						if (exptTable == null) {
							opts.settings.searchParam = {
								"brandCode" : mainCtrl.brandCode,
								"categoryCode" : "",
								"storeCode" : "",
								"pageNo" : 1,
								"pageSize" : 10,
							}
							exptTable = SwiftUI.swiftTable.getInstance(opts);
						}

					},
					error : function(err) {
						console.log(err);
					}
				});
	}
	
	// 根据大区查公司
	function getBranchByCode(regionCode) {
		var allBranchList = mainCtrl.allBranch, allBranchLen = allBranchList.length, newBranch = [];
		if (regionCode == "") {
//			newBranch = allBranchList;
		} else {
			for (var i = 0; i < allBranchLen; i++) {
				if (allBranchList[i].pid == regionCode) {
					newBranch.push({
						"id" : allBranchList[i].id,
						"text" : allBranchList[i].text,
						"pid" : regionCode
					});
				}
			}
		}
		var alljsonData = [];
		for (var i = 0; i < newBranch.length; i++) {
			alljsonData.push({
				id : newBranch[i].id,
				name : newBranch[i].id + "-" + newBranch[i].text,
				pid : newBranch[i].pid
			});
		}
		magicBranch.setData(alljsonData);

	}

	// 根据分公司查门店
	function getStoresByCode(branchCode) {
		var rid = $("#magicRegion .m-id").val();
		var allStoreList = mainCtrl.allStore, allStoreLen = allStoreList.length, newStore = []
		,allBranchList = mainCtrl.allBranch, allBranchLen = allBranchList.length;
		if (!branchCode ) {
			//获取大区下所有门店信息
			for (var i = 0; i < allBranchLen; i++) {
				if (allBranchList[i].pid == rid) {
					for (var k = 0; k < allStoreLen; k++) {
						if (allStoreList[k].pid == allBranchList[i].id) {
							newStore.push({
								"id" : allStoreList[k].id,
								"text" : allStoreList[k].text,
								"pid" :  allStoreList[k].pid
							});
						}
					}
				}
			}
		} else {
			for (var i = 0; i < allStoreLen; i++) {
				if (allStoreList[i].pid == branchCode) {
					newStore.push({
						"id" : allStoreList[i].id,
						"text" : allStoreList[i].text,
						"pid" : branchCode
					});
				}
			}
		}
		var alljsonData = [];
		for (var i = 0; i < newStore.length; i++) {
			alljsonData.push({
				id : newStore[i].id,
				name : newStore[i].id + "-" + newStore[i].text,
				pid : newStore[i].pid
			});
		}
		magicStore.setData(alljsonData);

	}
//    getAllStores();
	getRegionBranch();

    avalon.scan();
});